import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.StringTokenizer;


public class GravitationalObject extends SpaceObject
{
	protected static final int RADIUS = 8; // radius of the object
	
	// constant factor in gravitational force
	private final double strength = 12000;
	
	// for obejects close than this distance, the force does not grow larger
	// to prevent spaceships from shooting off at huge speeds if they get too
	// close to the planet
	private final double minDistance = 60;
	private BufferedImage image;
	
	private boolean visible;
	
	public GravitationalObject(boolean visible)
	{
		// always in middle of screen
		super(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
		this.visible = visible;
		
		drawImage();
	}
	
	public GravitationalObject(StringTokenizer strtok)
	{
		super();
		loadState(strtok);
		
		drawImage();
	}
	
	// Implements getImage of SpaceObject
	public BufferedImage getImage() { return image; }
	
	// Implement collision functions
	public CollisionType collisionType() 
	{
		if(visible)
			return CollisionType.CIRCLE; 
		return CollisionType.NONE;
	}
	public double[] collisionData()
	{
		// center + radius
		double[] circle = {x, y, RADIUS};
		return circle;
	}
	
	private void drawImage()
	{
		if(!visible)
			image = null;
		else
		{
    		image = new BufferedImage(RADIUS*2, RADIUS*2, BufferedImage.TYPE_INT_ARGB);
    		Graphics2D g = image.createGraphics();
    		
    		g.setColor(Color.WHITE);
    		g.fillOval(0,0, RADIUS*2, RADIUS*2);
    		g.dispose();
		}
	}
	
	public boolean hit(SpaceObject other)
	{
		// Gravitational objects are never affected by a collision
		return false;
	}
	
	protected void loadState(StringTokenizer strtok) throws NumberFormatException
	{
		super.loadState(strtok);
		visible = Boolean.parseBoolean(strtok.nextToken());
	}
	protected String saveState()
	{
		return "GravitationalObject " + super.saveState() + String.format("%s\n", visible);
	}
	
	public double forceMag(SpaceObject other)
	{
		double sqDist = squareDistance(other);
		return strength * 1/Math.max(sqDist, minDistance*minDistance);
	}
}
